package forms

import (
	"errors"
	valid "github.com/go-ozzo/ozzo-validation"
	"github.com/go-ozzo/ozzo-validation/is"
	"titargo/models"

)

type RegisterForm struct {
	Email      string `form:"email",json:"email"`
	Username   string `form:"username",json:"username"`
	Password   string `form:"password",json:"password"`
	Repassword string `form:"repassword",json:"repassword"`
	user        *models.User
}

func (l *RegisterForm) Validate() error {
	err := valid.ValidateStruct(l,
		valid.Field(&l.Email, valid.Required.Error("邮箱不能为空"),is.Email.Error("不是个正确的邮箱")),
		valid.Field(&l.Username, valid.Required.Error("用户名不能为空")),
		valid.Field(&l.Password, valid.Required.Error("密码不能为空")),
		valid.Field(&l.Repassword, valid.Required.Error("重复密码不能为空")),
	)
	if err != nil {
		return err
	}

	if l.Password != l.Repassword {
		return errors.New("重复密码不正确")
	}

	db := models.GetEngine()
	db.Where("username = ? or email = ?", l.Username, l.Email)

	if has,_:=db.Exist();has==true{
		return errors.New("用户名或邮箱已存在")
	}

	l.user = &models.User{Email: l.Email, Username: l.Username,Password:l.Password}
	return nil
}

func (l RegisterForm) GetUser() *models.User {
	return l.user
}